package org.uim.cricket.analyzer.analyze.impl;

import java.util.List;
import java.util.Map;

import org.uim.cricket.analyzer.analyze.AnalyzerCommonFunctions;
import org.uim.cricket.analyzer.analyze.CricketMatchAnalyzable;
import org.uim.cricket.entities.MatchPlayer;
import org.uim.cricket.entities.Player;

public abstract class PlayerListFinderAnalyzer implements CricketMatchAnalyzable {

	private AnalyzerCommonFunctions analyzerFuncs = new AnalyzerCommonFunctions();
	
	private boolean setNullIfNotFound = true;
	
	
	private MatchPlayer findSuitablePlayer(Map<String, List<MatchPlayer>> players, Player p) {
		
		for (String team : players.keySet()) {
			List<MatchPlayer> searchOn = players.get(team);
			
			int index = this.analyzerFuncs.containInMatchPlayerList(searchOn, p.getTitleName());
			if (index >= 0) return searchOn.get(index);
		}
		
		return null;
	}

	protected void startFinding(Map<String, List<MatchPlayer>> players, Player p) {
		if (p == null) return;
		
		List<MatchPlayer> searchOn = null;
		if (p.getCountry() != null && p.getCountry().length() > 0) {
			searchOn = players.get(p.getCountry());
		}
		
		if (searchOn == null) {
			
			MatchPlayer mp = this.findSuitablePlayer(players, p);
			if (mp != null) {
				p = mp.getPlayer();
			} else {
				p = null;
			}
			
		} else {
			
			int index = this.analyzerFuncs.containInMatchPlayerList(searchOn, p.getTitleName());
			if (index >= 0) {
				p = searchOn.get(index).getPlayer();
			} else {
				MatchPlayer mp = this.findSuitablePlayer(players, p);
				if (mp != null) {
					p = mp.getPlayer();
				} else {
					p = null;
				}
			}
			
		}
		
	}
	
	protected void startFinding(Map<String, List<MatchPlayer>> players, Player[] ps) {
		if (ps == null) return;
		
		for (int i=0;i<ps.length;i++) {
			this.startFinding(players, ps[i]);
		}
	}
	
	protected void startFinding(Map<String, List<MatchPlayer>> players, List<Player> ps) {
		if (ps == null) return;
		
		for (int i=0;i<ps.size();i++) {
			this.startFinding(players, ps.get(i));
		}
	}
	
	public void setSetNullIfNotFound(boolean setNullIfNotFound) {
		this.setNullIfNotFound = setNullIfNotFound;
	}
	
	public boolean isSetNullIfNotFound() {
		return setNullIfNotFound;
	}
}
